from celery import shared_task
import time

@shared_task
def add(x, y):
    time.sleep(5)
    return x + y


@shared_task
def mul(x, y):
    return x * y


@shared_task
def xsum(numbers):
    return sum(numbers)


from apps.crm.models import CheckingIn, User, CheckingInStatistics
from django.db.models import Max, Min
@shared_task
def checking_in_statistics():
    # result = CheckingIn.objects.all().values('date', 'user').annotate(sign_time=Min('sign_time'), leave_time=Max('sign_time'))
    # 找出当天考勤记录的签到签退时间
    cur_result = CheckingIn.objects.filter(date__year=2017, date__month=10, date__day=30).values('user').annotate(
        start_time=Min('sign_time'), leave_time=Max('sign_time'))
    # 找出所有用户 # 有的用户is_active
    alluser = User.objects.all()
    # 找出节假日
    for user in alluser:
        # 如果user存在cur_result。
        t_result = cur_result.filter(user=user)
        if t_result:
            t_result = t_result[0]
            print(t_result)
            checkinstatus = CheckingInStatistics(user=user, date='2017-10-30',sign_time=t_result["start_time"], leave_time=t_result["leave_time"])
            print(checkinstatus)
            if str(t_result["start_time"]) <= "09:00:00" and str(t_result["leave_time"]) >= "17:00:00":
                print(user, 'check ok')
                checkinstatus.status = 1
            else:
                checkinstatus.status = 0
                print(user, 'check error')
            # if not checkinstatus:
            checkinstatus.save()
        # 否则计算，否则直接记录为异常
        else:
            checkinstatus = CheckingInStatistics(user=user, date='2017-10-30', status=0)
            checkinstatus.save()
            print(user,'error')
    print(cur_result)
    return 'hello'
